/*
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.datastore.server;

import java.util.Date;
import java.util.List;

import com.datastore.client.Account;
import com.datastore.client.DataStoreService;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class DataStoreServiceImpl extends RemoteServiceServlet implements DataStoreService {

  @Override
  public void StoringData(String username,String password) {

  Key accoutKey = KeyFactory.createKey("Account", "default");
  Date date = new Date();
  Entity greeting = new Entity("Account",accoutKey);
  greeting.setProperty("username", username);
  greeting.setProperty("date", date);
  greeting.setProperty("password", password);
  
  DatastoreService dataStore = DatastoreServiceFactory.getDatastoreService();
  dataStore.put(greeting);
  }

  @Override
  public Account[] getAccountData() {
    // TODO Auto-generated method stub
    Account[] accounts = new Account[5];
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Key guestbookKey = KeyFactory.createKey("Account", "default");
    Query query = new Query("Account",guestbookKey).addSort("date", Query.SortDirection.DESCENDING);
    List<Entity> greetings = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
    int i = 0;
    for(Entity greeting : greetings){
        accounts[i] = new Account(String.valueOf(greeting.getProperty("username")),
            String.valueOf(greeting.getProperty("password")),String.valueOf(greeting.getProperty("date")));
        ++i;
    }
    return accounts;
  }
}
